package jsu.yym.tiktok.test;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jsu.yym.tiktok.pojo.User;
import jsu.yym.tiktok.server.MD5Get;
import jsu.yym.tiktok.service.SearchService;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.junit.jupiter.api.Test;
import org.springframework.stereotype.Service;

import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import jsu.yym.tiktok.pojo.Video;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/***
 * es相关类，实现创建索引库，添加数据
 */
@Service
public class VideoElasticsearchService {
    @Test
    void es() throws Exception {
//        Video video =  new Video("hhhh",1,"你好");
//        saveVideoToElasticsearch(video);
//        User user = new User("123","张三");
//        savaUserToEs(user);
//        closeElasticsearchClient();
        System.out.println(new MD5Get().getMD5("1234567"));
    }
    private final RestHighLevelClient elasticsearchClient;

    public VideoElasticsearchService() {
        // 初始化 Elasticsearch 客户端
        elasticsearchClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http")));
    }

    public void saveVideoToElasticsearch(Video video) {
        try {
            // 创建索引请求
            IndexRequest indexRequest = new IndexRequest("video"); // 替换为你的索引名称
            indexRequest.id(String.valueOf(video.getPkId())); // 使用 Video 对象的 pkId 作为文档 ID
            String json = videoToJson(video); // 将 Video 对象转为 JSON 字符串
            indexRequest.source(json, XContentType.JSON);

            // 执行索引请求
            elasticsearchClient.index(indexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            // 处理异常
            e.printStackTrace();
        }
    }

    public void savaUserToEs(User user){
        try {
            // 创建索引请求
            IndexRequest indexRequest = new IndexRequest("user"); // 替换为你的索引名称
            indexRequest.id(String.valueOf(user.getUsername())); // 使用 User 对象的 Username 作为文档 ID
            String json = userToJson(user); // 将 User 对象转为 JSON 字符串
            indexRequest.source(json, XContentType.JSON);

            // 执行索引请求
            elasticsearchClient.index(indexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            // 处理异常
            e.printStackTrace();
        }
    }

    private String userToJson(User user) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(user);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return "";
        }
    }

    private String videoToJson(Video video) {
        // 这里你可以使用 JSON 序列化库将 Video 对象转为 JSON 字符串
        // 你可以使用 Jackson、Gson 等库来进行转换
        // 以下示例使用 Jackson：
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(video);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return "";
        }
    }

    // 关闭 Elasticsearch 客户端
    public void closeElasticsearchClient() {
        try {
            elasticsearchClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 你需要实现获取视频数据的方法
    public List<Video> getVideoData(String id) {
        // 这里返回你的 Video 数据集合
//        List<Video> videos  = videoMapper.getVideoByState(1);
        List<Video> videos = new ArrayList<>();

        //根据用户id获取她所有关注的人的id
//        List<String> idList = fansMapper.getPersonIdsByUsername(id);
//        List<Video> videoList = videoMapper.getVideosByUsernamesAndState(idList,)

        return videos;
    }


    //将集合存入es中
    public void addListToES(String id){
        SearchService searchService = new SearchService();
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http"))
        );

        // 要插入的视频数据集合
        List<Video> videoList = getVideoData(id);  // 你需要实现获取视频数据的方法

        BulkRequest bulkRequest = new BulkRequest();
        for (Video video : videoList) {
            String videoJson = videoToJson(video);  // 将 Video 对象转换为 JSON 字符串
            bulkRequest.add(new IndexRequest("your_index_name")
                    .id(String.valueOf(video.getPkId()))  // 使用视频的唯一标识作为文档 ID
                    .source(videoJson, XContentType.JSON));
        }

        try {
            BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
            if (bulkResponse.hasFailures()) {
                System.err.println("部分文档插入失败：" + bulkResponse.buildFailureMessage());
            } else {
                System.out.println("所有文档插入成功");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

